package com.mars.boss.web.controller;

import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mars.web.common.support.BaseController;
import com.mzlion.easyokhttp.HttpClient;

@Controller
public class LoginController extends BaseController {
	
	private static final String APPID = "wx6358bba8639abf18" ;
	private static final String APPSECRET = "d4624c36b6795d1d99dcf0547af5443d" ;
	
	@RequestMapping(value = "/login")
	public String main() {
		return "login" ;
	}
	
	@RequestMapping(value = "/process")
	public void process() {
		
	}

	
	@RequestMapping(value = "/wx_login")
	public String wx_login() {
		return "wx_login" ;
	}
	
	@RequestMapping(value = "/wx_login_process", method=RequestMethod.GET)
	@ResponseBody
	public void wx_login_process() {
		String callbackUrl = "http://yhaoquan.imwork.net/wx_login_callback" ;
		
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize"
				+ "?appid="+APPID
				+ "&redirect_uri="+callbackUrl
				+ "&response_type=code"
				+ "&scope=snsapi_userinfo"
				+ "&state=STATE#wechat_redirect" ;
		
		try {
			this.response.sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/wx_login_callback", method=RequestMethod.GET)
	public String wx_login_callback() {
		String code = this.request.getParameter("code") ;
		System.out.println("code: " + code);
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token"
				+ "?appid="+APPID
				+ "&secret="+APPSECRET
				+ "&code="+code
				+ "&grant_type=authorization_code" ;
		
		String asString = HttpClient.get(url).execute().asString();
		JSONObject parseObject = JSON.parseObject(asString) ;
		
		System.out.println("asString: " + asString);
		
		String userinfoURL = "https://api.weixin.qq.com/sns/userinfo"
				+ "?access_token="+parseObject.get("access_token")
				+ "&openid="+parseObject.get("openid")
				+ "&lang=zh_CN" ;
		
		String userinfo = HttpClient.get(userinfoURL).execute().asString();
		
		System.out.println("userinfo: " + userinfo);
		this.request.setAttribute("userinfo", userinfo);
		
		return "wx_login_success" ;
	}


	@RequestMapping(value = "/wx_login_bind_process")
	public Object wx_login_bind_process() {
		return setResponseResultOk() ;
	}
	
}
